<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script>
        var socket;
        //判断当前浏览器是否支持websocket
        if(window.WebSocket){
            socket = new WebSocket("ws://localhost:7000/hello");
            //回调函数，有消息到来时执行
            socket.onmessage = function (ev) {
                var rt = document.getElementById("response");
                rt.value += "\n" + ev.data;
            }
            //连接开启
            socket.onopen = function (ev) {
                var rt = document.getElementById("response");
                rt.value = "连接开启了";
            }
            //连接关闭
            socket.onclose = function (ev) {
                var rt = document.getElementById("response");
                rt.value += "\n" + "连接关闭了";
            }
        }else {
            alert("当前浏览器不支持websocket");
        }

        //发送消息给服务器
        function send(message) {
            if (!window.socket) return;

            if (socket.readyState == WebSocket.OPEN){
                socket.send(message);
            }else {
                alert("连接未开启");
            }
        }
    </script>

    <form onsubmit="return false">
        <textarea name="message" style="height: 300px;width: 200px"></textarea>
        <input type="button" value="发送消息" onclick="send(this.form.message.value)">
        <textarea id="response" style="height: 300px;width: 200px"></textarea>
        <input type="button" value="清空内容" onclick="document.getElementById('response').value = ''">
    </form>
</body>
</html>